<template>
  <div>
    <!-- add todo-->
    <EditTodo v-model:todoTitle="newTodo"
              @keyup.enter="addTodo"
              autofocus
              placeholder="新增今日待办"
              autocomplete="off"
    ></EditTodo>

    <!-- todo list-->
    <ul>
      <TodoItem v-for="todo in filterTodo"
                :key="todo.id"
                v-model:editId="editId"
                :todo="todo"
                @removeTodo="removeTodo"
      ></TodoItem>
    </ul>

    <Filter :items="filterItems" v-model="visibility"></Filter>
<!--    返回到看板-->
    <button @click="backToDash">back</button>
  </div>
</template>

<script>
import {reactive, toRefs, watch} from 'vue'
import TodoItem from "./TodoItem.vue";
import Filter from "./Filter.vue";
import useTodos from "./useTodos.js"
import useFilter from "./useFilter.js"

import {useRouter, useRoute, onBeforeRouteLeave} from 'vue-router'
// watchEffect 当数据变化 就save


export default {
  components: {
    TodoItem,
    Filter
  },
  setup() {
    const todoState = reactive({
      newTodo: '',
      editId: null,
    })
    const {todoList, addTodo, removeTodo} = useTodos(todoState)
    const filterState = useFilter(todoList)

    // 获取路由器的实例
    const router = useRouter()

    // route 是响应对象，可监控其变化
    const route = useRoute()
    watch(() => route.query,(query) => {
      console.log(query);
    })

    // 守卫
    // 打算离开之前
    onBeforeRouteLeave((to, from) => {
      const answer = window.confirm('你确定要离开当前页面吗')
      if(!answer) {
        return false
      }
    })
    return {
      ...toRefs(todoState),
      ...toRefs(filterState),
      todoList,
      addTodo,
      removeTodo,
      backToDash() {
        router.push('/')
      }
    }
  }

}
</script>

<style scoped>

</style>
